package com.zys.sac.core.handler;

import com.zys.sac.core.constant.RequestStatus;
import com.zys.sac.core.helper.TokenManager;
import com.zys.sac.core.util.ServletResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt方式的验证成功处理器，当登录成功后会调用该类的onAuthenticationSuccess方法
 *
 * Created by zhongjunkai on 2022/3/11.
 */
@Slf4j
public class SacJwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private TokenManager tokenManager;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        UserDetails user = (UserDetails) authentication.getPrincipal();
        String token = null;
        try {
            token = tokenManager.createAndSaveToken(user);
        } catch (Exception e) {
            log.error("认证成功后发生异常：{}", e);
            ServletResponseUtils.render(httpServletResponse, ServletResponseUtils.result(RequestStatus.INVALIDTOKEN.getCode(), RequestStatus.INVALIDTOKEN.getMsg()));
            return;
        }
        ServletResponseUtils.render(httpServletResponse, ServletResponseUtils.result(RequestStatus.SUCCESS.getCode(), RequestStatus.SUCCESS.getMsg(), token));
    }


}
